<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Db;
use app\admin\model\Admin as AdminModel;

class Index extends Base
{
	
    public function index()
    {
        return $this->fetch();
    }
	
	public function edit()
    {
		$id = input('id');
		$admins = db('admin')->where('id',$id)->find();
		if(request()->isPost()){
			$data = [
				'id' =>input('id'),
				'username'=>input('username'),
			];
			
			if(input('password')){
				$data['password']=md5(input('password'));
			}else{
				$data['password']=$admins['password'];
			}
			
			// 验证
			$validate = \think\Loader::validate('Admin');
			if(!$validate->check($data)){
			    $this->error($validate->getError());
				die;
			}
			
			$save = db('admin')->update($data);
			if($save !== false){
				$this->success('修改成功！','lst');
			}else{
				$this->error('修改失败！');
			}
			return;
		}
		
		
		$this->assign('admins',$admins);
        return $this->fetch();
    }
    
    public function add()
    {	
		if(request()->isPost()){
			// 接收数据
			$data=[
				'username'=>input('username'),
				'password'=>md5(input('password')),
			];
			
			// 验证
			$validate = \think\Loader::validate('Admin');
			if(!$validate->check($data)){
			    $this->error($validate->getError());
				die;
			}
			
			// 判断结果
			if(Db::name('admin')->insert($data)){
				return $this->success('添加管理员成功','lst');
			}else{
				return $this->error('添加管理员失败');
			}
			return;
		}
        return $this->fetch('add');
    }
    
    public function lst()
    {	
		$list = AdminModel::paginate(5);
		$this->assign('list',$list);
        return $this->fetch('lst');
    }
	
	public function del(){
		$id = input('id');
		if($id!=2){
			if(db('admin')->delete(input('id'))){
				$this->success('删除管理员成功','lst');
			}else{
				$this->error('删除管理员失败');
			}
		}else{
			$this->error('初始化管理员不能删除');
		}
	}
	
	public function logout(){
		session(null);
		$this->success('退出登录成功','login/index');
	}
	
	
}
